package com.bilibili.juc.cas;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @author zuife
 * @description
 * 单线程环境下简单场景
 * @since 2024-05-02 22:17:55
 */
public class AtomicStampedDemo {
    public static void main(String[] args) {
        Book javaBook = new Book("javaBook", 1);
        AtomicStampedReference<Book> bookAtomicStampedReference = new AtomicStampedReference<>(javaBook, 1);
        System.out.println(bookAtomicStampedReference.getReference() + "\t" + bookAtomicStampedReference.getStamp());
        Book mysqlBook = new Book("mysqlBook", 2);
        boolean b = bookAtomicStampedReference.compareAndSet(javaBook, mysqlBook, bookAtomicStampedReference.getStamp(), bookAtomicStampedReference.getStamp() + 1);
        System.out.println(b + "\t" + bookAtomicStampedReference.getReference() + "\t" + bookAtomicStampedReference.getStamp());

        boolean b1 = bookAtomicStampedReference.compareAndSet(mysqlBook, javaBook, bookAtomicStampedReference.getStamp(), bookAtomicStampedReference.getStamp() + 1);
        System.out.println(b1 + "\t" + bookAtomicStampedReference.getReference() + "\t" + bookAtomicStampedReference.getStamp());
    }
}

@NoArgsConstructor
@AllArgsConstructor
@Data
class Book {
    String bookName;
    int id;
}
